/* 导入针对性解析器 */
const parserBDPWI = require('./parserBDPWI.js')
const parserBDTCI = require('./parserBDTCI.js')
const parserBDFKI = require('./parserBDFKI.js')
/**
 * UDP服务器创建
 */
const fs = require('fs')
const path = require('path')
const dgram = require('dgram')
const server = dgram.createSocket('udp4')
let config = JSON.parse(fs.readFileSync(path.join(process.cwd(), './config.json')))
server.on('listening', () => {
	const address = server.address()
	console.log(`开启udp服务端主机:${address.address}`)
	console.log(`udp服务端端口:${address.port}`)
	// 开启广播
	server.setBroadcast(true)
	// 发消息这样发server.send('hello', config.udpServerSendPort, config.udpServerGB)
	// ###warning->注意要跨网段，需要设置子网掩码255.255.0.0然后广播地址192.168.0.0###
})
server.on('message', (msg, remoteInfo) => {
	console.log(`udp服务器收到消息:${msg},来自于${remoteInfo.address}:${remoteInfo.port}`)
})
server.on('error', (err) => {
	console.log(`udp服务器报错:${err}`)
})
server.bind(config.udpServerPort)

/* mian解析器入口 */
function mainParser(arrayData, port) {
	const head = arrayData[0]
	if (head === '$BDPWI') {
		parserBDPWI(arrayData, port, config, server)
	} else if (head === '$BDTCI') {
		parserBDTCI(arrayData, server, config)
	} else if (head === '$BDFKI') {
		parserBDFKI(arrayData)
	}
}

module.exports = { mainParser }
